package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.BaseInfoDto;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private AdvimgService advimgService;

    @Autowired
    private AdvposService advposService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CateService cateService;

    @Autowired
    private TagService tagService;

    @Autowired
    private YddUserService yddUserService;

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultData login(@RequestBody User user) {
        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLogin_name, user.getLogin_name());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String roleId = loginUser.getRole_id()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

        }
        return ResultData.ok("", retMap);
    }


    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {
        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttr_key(), config.getAttr_value());
        }
        return ResultData.ok("", map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }


    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }

    //主页信息统计
    @GetMapping("/baseInfo")
    public ResultData baseInfo() {
        BaseInfoDto baseInfoDto = new BaseInfoDto();
        List<Cate> list = cateService.list();
        List<CateDto> cateDtos = list.stream().map(item -> {
            CateDto cateDto = new CateDto();
            BeanUtils.copyProperties(item, cateDto);
            LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Article::getCateid, item.getId());
            int count = articleService.count(queryWrapper);
            cateDto.setNum(count);
            return cateDto;
        }).collect(Collectors.toList());
        //文章分类
        baseInfoDto.setAllCateList(cateDtos);

        //广告位总数
        baseInfoDto.setAdvposNum(advposService.count());

        //标签总数
        baseInfoDto.setTagNum(tagService.count());

        //管理员总数
        baseInfoDto.setAdminNum(userService.count());

        //文章总数
        baseInfoDto.setArticleNum(articleService.count());

        //分类总数
        baseInfoDto.setCateNum(cateService.count());

        //广告总数
        baseInfoDto.setAdvimgNum(advimgService.count());

        //最新用户数据
        LambdaQueryWrapper<YddUser> queryWrapperUser=new LambdaQueryWrapper<>();
        queryWrapperUser.select(YddUser::getId,YddUser::getUsername,YddUser::getSex,YddUser::getIcon,YddUser::getAddress);
        queryWrapperUser.orderByDesc(YddUser::getId);
        queryWrapperUser.last("limit 7");
        List<YddUser> yddUsers = yddUserService.list(queryWrapperUser);
        baseInfoDto.setNewUserList(yddUsers);

        //热门文章数据
        LambdaQueryWrapper<Article> queryWrapperArticle=new LambdaQueryWrapper<>();
        queryWrapperArticle.select(Article::getId,Article::getTitle,Article::getAuthor,Article::getKeywords,Article::getClick);
        queryWrapperArticle.orderByDesc(Article::getClick);
        queryWrapperArticle.last("limit 7");
        List<Article> articleList = articleService.list(queryWrapperArticle);
        baseInfoDto.setHotArticleList(articleList);

        //用户数据
        UserDto userDto = new UserDto();
        LambdaQueryWrapper<YddUser> yddUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        yddUserLambdaQueryWrapper.eq(YddUser::getSex,0);
        int countMan = yddUserService.count(yddUserLambdaQueryWrapper);
        int total = yddUserService.count();
        userDto.setTotal(total);
        userDto.setUserMan(countMan);
        userDto.setUserWoman(total-countMan);
        baseInfoDto.setUser(userDto);

        return ResultData.ok("主页信息查询已完成", baseInfoDto);
    }
}
